import {
  Button,
  Card,
  Col,
  Divider,
  Form,
  message,
  Row,
  Switch,
  theme
} from "antd"
import React, { useEffect, useState } from "react"

import { sendToBackground, sendToContentScript } from "@plasmohq/messaging"
import { useStorage } from "@plasmohq/storage/hook"

import "~style.css"

import { useForm } from "antd/es/form/Form"

import { useUIcontentStore } from "~store/uicontentStore"
import { ThemeProvider } from "~theme"
import type { UIContentState } from "~type/UIcontent"

function IndexPopup() {
  const { showUI, setShowUI } = useUIcontentStore()
  const [AiEnable, setAiEnable] = useState<boolean>(false)
  const onAiEnable = async (checked: boolean) => {
    setAiEnable(checked)
  }
  const [uiForm] = useForm<UIContentState>()
  const sendAiEnable = async ({ showUI = false }: UIContentState) => {
    await sendToContentScript<UIContentState>({
      name: "AiEnable",
      body: {
        showUI: showUI
      }
    })

    setShowUI(showUI)
  }
  useEffect(() => {
    // console.log("initData")
    // console.log("showUI", showUI)
    if (showUI != undefined) {
      uiForm.setFieldsValue({ showUI })
      sendAiEnable({ showUI })
    }
  }, [])

  const onValusChange = (
    changedValues: UIContentState,
    values: UIContentState
  ) => {
    for (const historyState in changedValues) {
      if (historyState === "showUI") {
        uiForm.submit()
      }
    }
  }
  function onFinsh(values: UIContentState): void {
    sendAiEnable({ showUI: values.showUI })
  }

  return (
    <ThemeProvider>
      <div className="p-[.25rem]  ">
        <Form
          form={uiForm}
          name="uiform"
          onValuesChange={onValusChange}
          onFinish={onFinsh}>
          <Form.Item name="showUI">
            <Switch
              checkedChildren={"ChatUI"}
              unCheckedChildren={"ChatUI"}></Switch>
          </Form.Item>
        </Form>
      </div>
    </ThemeProvider>
  )
}

export default IndexPopup
